<template>
  <div>
    <el-card shadow="hover" :body-style="{ padding: '20px' }">
      <el-button
        type="primary"
        size="default"
        :icon="Plus"
        @click="addTrademark"
        v-has="`btn.Trademark.add`"
        >添加品牌</el-button
      >
      <el-table :data="records" :border="true" style="margin-top: 10px">
        <el-table-column
          align="center"
          label="序号"
          prop="id"
          width="90"
        ></el-table-column>
        <el-table-column prop="tmName" label="品牌名称"></el-table-column>
        <el-table-column label="品牌LOGO">
          <template #="{ row }">
            <img
              :src="row.logoUrl"
              alt=""
              style="width: 100px; height: 100px"
            />
          </template>
        </el-table-column>
        <el-table-column width="200" label="操作">
          <template #="{ row, $index }">
            <el-button
              type="warning"
              size="small"
              :icon="Edit"
              @click="updateTrademarkInfo(row)"
              v-has="`btn.Trademark.update`"
            >
            </el-button>
            <el-popconfirm
              :title="`你确定要删除${row.tmName}?`"
              :icon="Delete"
              width="200px"
              confirm-button-text="确定"
              cancel-button-text="取消"
              @confirm="deleteTrademarkInfo(row)"
            >
              <template #reference>
                <el-button type="danger" size="small" :icon="Delete" v-has="`btn.Trademark.remove`">
                </el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <el-pagination
      v-model:currentPage="currentPage"
      v-model:pageSize="pageSize"
      style="margin-top: 10px"
      :small="false"
      layout=" prev , pager , next , jumper , ->  ,sizes , total "
      :total="total"
      class="mt-4"
      :page-sizes="[3, 5, 7, 9]"
      @current-change="getTrademarkInfo"
      @size-change="sizeChange"
    />
    <!--模态框组件-->
    <el-dialog
      v-model="dialogFormVisible"
      :title="tmParams.id ? '修改品牌内容' : '添加品牌内容'"
      style="top: 100px"
      draggable
    >
      <el-form
        label-width="100px"
        :rules="rules"
        :model="tmParams"
        ref="tmForm"
      >
        <el-form-item label="品牌名称" style="width: 80%" prop="tmName">
          <el-input
            autocomplete="off"
            placeholder="请你输入品牌名称"
            v-model="tmParams.tmName"
          />
        </el-form-item>
        <el-form-item label="品牌LOGO" style="width: 80%" prop="logoUrl">
          <el-upload
            class="avatar-uploader"
            action="/app-dev/admin/product/fileUpload"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img
              v-if="tmParams.logoUrl"
              :src="tmParams.logoUrl"
              class="avatar"
            />
            <el-icon v-else class="avatar-uploader-icon"><Upload /></el-icon>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取消</el-button>
          <el-button type="primary" @click="addOrUpdateTrademark">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import type { UploadProps, FormInstance, FormRules } from "element-plus";
import { ElMessage } from "element-plus";
import { Plus, Edit, Delete, Upload } from "@element-plus/icons-vue";
import { nextTick, onMounted, reactive, ref } from "@vue/runtime-core";
import {
  reqAddOrUpdateTrademarkInfo,
  reqDeleteTrademarkInfo,
  reqTrademarkInfo,
} from "@/api/product/trademark/index";
import type {
  recordsType,
  trademarkModel,
  trademarkResponseData,
} from "@/api/product/trademark/model";

//设置初始的当前页码和展示数量
let currentPage = ref<number>(1);
let pageSize = ref<number>(3);

//存储响应回来的品牌数据
let records = ref<recordsType>([{ id: 0, tmName: "", logoUrl: "" }]);
let total = ref(0);

//定义模态框的值
let dialogFormVisible = ref(false);

//定义:新增品牌收集请求数据
let tmParams = reactive<trademarkModel>({
  tmName: "",
  logoUrl: "",
  id: 0,
});

//获取表单的DOM对象
let tmForm = ref();

//挂载发送请求获取品牌数据
onMounted(() => {
  getTrademarkInfo();
});
//发送请求获取数据
const getTrademarkInfo = async (pageNo = 1) => {
  //发请求之前:先整理参数
  currentPage.value = pageNo;
  let result: trademarkResponseData = await reqTrademarkInfo(
    currentPage.value,
    pageSize.value
  );
  records.value = result.records;
  total.value = result.total;
};
//页面展示数据条数的事件回调
const sizeChange = async (pageSize1: number) => {
  pageSize.value = pageSize1;
  currentPage.value = 1;
  getTrademarkInfo();
};
//显示模态框
const addTrademark = () => {
  dialogFormVisible.value = true;
  // tmParams.logoUrl = ''
  // tmParams.tmName = ''
  //清空模态框发送成功之后的数据
  Object.assign(tmParams, { tmName: "", logoUrl: "" });
  //清空校验的信息
  tmForm.value?.clearValidate();
};
//上传路径的函数复制
const handleAvatarSuccess: UploadProps["onSuccess"] = (
  response,
  uploadFile
) => {
  tmParams.logoUrl = response.data;
};
//点击确定发送请求添加品牌
const beforeAvatarUpload: UploadProps["beforeUpload"] = (rawFile) => {
  if (
    rawFile.type == "image/jpeg" ||
    rawFile.type == "image/png" ||
    rawFile.type == "image/gif"
  ) {
    if (rawFile.size / 1024 / 1024 > 8) {
      return true;
    }
  } else {
    ElMessage.error("图片类型不正确或者图片过大");
  }
};
//点击发送按钮的回调 发送请求添加品牌数据 关dialog 弹信息 当前页为1 重新获取数据
const addOrUpdateTrademark = async () => {
  //通过ref获取表单元素 看看是否校验成功校验成功再发请求
  await tmForm.value.validate(); //全部表单项校验
  try {
    await reqAddOrUpdateTrademarkInfo(tmParams);
    dialogFormVisible.value = false;
    ElMessage.success(
      tmParams.id
        ? `修改${tmParams.tmName}品牌成功`
        : `添加${tmParams.tmName}品牌成功`
    );
    currentPage.value = 1;
    getTrademarkInfo();
  } catch (e) {
    ElMessage.error("上传图片失败");
    dialogFormVisible.value = false;
  }
};
//添加品牌内容的数据校验
// const rules = reactive<FormRules>({
//   tmName: [
//     { required: true, message: '品牌名字不能空的', trigger: 'blur' },
//     { min: 2, max: 10, message: '请你输入2-10为品牌名字', trigger: 'change' },
//   ],
// })

//品牌名称的校验函数
const validatortmName = (rule: any, value: any, callback: any) => {
  if (/^[\u4e00-\u9fa5]{4,}$/.test(value)) {
    callback();
  } else {
    callback(new Error("请保证品牌名称为4位以上的汉字"));
  }
};
//上传图片校验函数
const validatorLogoUrl = (rule: any, value: any, callback: any) => {
  if (value.length > 0) {
    callback();
  } else {
    callback(new Error("请您选择一张品牌图片"));
  }
};
//自定义校验函数
const rules = reactive<FormRules>({
  tmName: [{ required: true, trigger: "blur", validator: validatortmName }],
  logoUrl: [{ required: true, validator: validatorLogoUrl }],
});
//更新品牌信息
const updateTrademarkInfo = (row: any) => {
  dialogFormVisible.value = true;
  Object.assign(tmParams, row);
  //tmParams:收集修改请求参数,正好在dilog里面展示！！！
  nextTick(() => {
    tmParams.value.clearValidate("tmName");
    tmParams.value.clearValidate("logoUrl");
  });
};
//删除品牌信息
const deleteTrademarkInfo = async (row: any) => {
  try {
    let id = row.id;
    await reqDeleteTrademarkInfo(id);
    ElMessage.success(`删除${row.tmName}成功`);
    //当前页面数据删完之后如果小于1跳到前一页
    getTrademarkInfo(records.value.length>1?currentPage.value:currentPage.value-1);
  } catch (e) {
    ElMessage.error(`删除${row.tmName}失败`);
  } 
};
</script>

<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>